<template>
    <view class="app-container address">
        <zzk-nav title="新增/编辑商品"></zzk-nav>
        <view class="address-form">
            <view class="address-line flexrow">
                <view>
                    <text class="label">商品类目</text>
                </view>
                <view class="value flexrow select" @tap="showClassify = true">
                    <text class="txt gray" v-if="!params.categoryId">请选择商品类目</text>
                    <text class="txt" v-else>{{ params.categoryName }}</text>
                    <uni-icons type="right" size="16" color="#999"></uni-icons>
                </view>
            </view>
            <view class="address-line flexrow">
                <view>
                    <text class="label">商品名称</text>
                </view>
                <view class="value">
                    <up-input v-model="params.name" placeholder="请输入商品名称" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                </view>
            </view>
            <view class="address-line flexrow">
                <view>
                    <text class="label">商品单位</text>
                </view>
                <view class="value">
                    <up-input v-model="params.unit" placeholder="请输入商品单位,如:台" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                </view>
            </view>
            <view class="address-line flexrow">
                <view>
                    <text class="label">商品描述</text>
                </view>
                <view class="value">
                    <up-input v-model="params.description" placeholder="请输入商品描述" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                </view>
            </view>
            <view class="address-line flexrow">
                <view>
                    <text class="label">商品规格</text>
                </view>
                <view class="value">
                    <up-input v-model="params.spec" placeholder="请输入商品规格" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                </view>
            </view>
            <view class="address-line flexrow">
                <view>
                    <text class="label">商品图片</text>
                </view>
                <view class="value">
                    <image class="img" :src="pictureOssPath" mode="aspectFill" v-if="params.pictureOssPath" @tap="chooseImg"></image>
                    <view class="address-upload flexcolumn" @tap="chooseImg" v-else>
                        <uni-icons type="plusempty" size="20" color="#999"></uni-icons>
                        <text class="tip">上传图片</text>
                    </view>
                </view>
            </view>
            <view class="address-line flexrow">
                <view>
                    <text class="label">是否可换</text>
                </view>
                <view class="value flexcolumn f">
                    <up-switch v-model="exchangable" size="20" inactiveColor="#ccc"></up-switch>
                </view>
            </view>
            <template v-if="merchantRentable">
                <view class="address-line flexrow">
                    <view>
                        <text class="label">是否可租</text>
                    </view>
                    <view class="value flexcolumn f">
                        <up-switch v-model="rentable" size="20" inactiveColor="#ccc"></up-switch>
                    </view>
                </view>
                <!-- 出租 -->
                <template v-if="rentable">
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">押金</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.deposit" type="digit" placeholder="请输入商品押金" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">年租金</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.priceForYear" type="digit" placeholder="请输入年租金" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">月租金</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.priceForMonth" type="digit" placeholder="请输入月租金" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">周租金</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.priceForWeek" type="digit" placeholder="请输入周租金" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                </template>
            </template>
            <template v-if="merchantMarketable">
                <view class="address-line flexrow">
                    <view>
                        <text class="label">是否可售</text>
                    </view>
                    <view class="value flexcolumn f">
                        <up-switch v-model="marketable" size="20" inactiveColor="#ccc"></up-switch>
                    </view>
                </view>
                <template v-if="marketable">
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">零售价</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.price" type="digit" placeholder="请输入商品零售价" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">vip价</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.vipPrice" type="digit" placeholder="请输入商品vip价" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                    <view class="address-line flexrow">
                        <view>
                            <text class="label">批发价</text>
                        </view>
                        <view class="value">
                            <up-input v-model="params.wholeSalePrice" type="digit" placeholder="请输入商品批发价" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                        </view>
                    </view>
                </template>
            </template>
            <template v-if="rentable || marketable || exchangable">
                <view class="address-line flexrow">
                    <view>
                        <text class="label">交付方式</text>
                    </view>
                    <view class="value flexrow tags">
                        <text 
                            class="tag" 
                            v-for="(tag, t) in logisticsType" 
                            :key="t"
                            :class="{ active: params.deliveryTypes.includes(tag.value) }"
                            @tap="changeTag(tag.value)">{{ tag.name }}</text>
                    </view>
                </view>
                <view class="address-line flexrow">
                    <view>
                        <text class="label">配送价</text>
                    </view>
                    <view class="value">
                        <up-input v-model="params.deliveryPrice" type="digit" placeholder="请输入配送价" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                    </view>
                </view>
                <view class="address-line flexrow">
                    <view>
                        <text class="label">运费</text>
                    </view>
                    <view class="value">
                        <up-input v-model="params.logisticsFee" type="digit" placeholder="请输入运费" border="none" clearable :customStyle="{ height: '80rpx', fontSize: '28rpx' }"></up-input>
                    </view>
                </view>
            </template>
        </view>
        <zzk-bottom>
            <view class="address-bottom flexrow">
                <up-button type="primary" text="保存" :loading="loading" @click="onSubmit"></up-button>
            </view>
        </zzk-bottom>
        <up-picker :show="showClassify" :columns="[classify]" keyName="name" @cancel="showClassify = false" @confirm="selectClassify"></up-picker>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { onLoad } from '@dcloudio/uni-app'
import { uploadFile } from '@/api/upload.js'
import { goodsCategories, addGoods, goodsInfo } from '@/api/goods.js'
import { showToast, backpage, bcmul, bcdiv } from '@/utils/util'
import WxValidate from '@/utils/WxValidate.js'

const store = useStore()
const merchantRentable = computed(() => store.state.user.rentable)
const merchantMarketable = computed(() => store.state.user.marketable)

const pictureOssPath = ref('')
const rentable = ref(false)
const marketable = ref(false)
const exchangable = ref(false)
const logisticsType = ref([
    { name: '商家配送上门', value: 'MERCHANT_SEND' },
    { name: '客户自提', value: 'CLIENT_SELF_PICKUP' },
    { name: '物流快递', value: 'LOGISTICS' }
])
const logistics = ref(0)
const params = ref({
    categoryId: '',
    categoryName: '',
    name: '',
    unit: '',
    description: '',
    spec: '',
    pictureOssPath: '',
    price: '',
    vipPrice: '',
    wholeSalePrice: '',
    deposit: '',
    rentable: 0,
    marketable: 0,
    exchangable: 0,
    deliveryTypes: [],
    deliveryPrice: '',
    logisticsFee: '',
    priceForYear: '',
    priceForMonth: '',
    priceForWeek: '',
})
const loading = ref(false)
const classify = ref([])
const showClassify = ref(false)

const id = ref('')

onLoad((option) => {
    getclassify()
    if (option.id) {
        id.value = option.id
    }
})

const getGoodsInfo = () => {
    goodsInfo(id.value).then(res => {
        rentable.value = res.rentable ? true : false
        marketable.value = res.marketable ? true : false
        exchangable.value = res.exchangable ? true : false
        pictureOssPath.value = res.pictureOssPath
        params.value = {
            categoryId: res.categoryId,
            categoryName: res.categoryName,
            name: res.goodsName,
            unit: res.unit || '',
            description: res.description,
            spec: res.spec,
            pictureOssPath: res.pictureOssPath,
            price: bcdiv(res.price, 100),
            vipPrice: bcdiv(res.vipPrice, 100),
            wholeSalePrice: bcdiv(res.wholeSalePrice, 100),
            deposit: bcdiv(res.deposit, 100),
            rentable: res.rentable ? 1 : 0,
            marketable: res.marketable ? 1 : 0,
            exchangable: res.exchangable ? 1 : 0,
            deliveryTypes: res.deliveryTypes.split(','),
            deliveryPrice: bcdiv(res.deliveryPrice, 100),
            logisticsFee: bcdiv(res.logisticsFee, 100),
            priceForYear: bcdiv(res.priceForYear, 100),
            priceForMonth: bcdiv(res.priceForMonth, 100),
            priceForWeek: bcdiv(res.priceForWeek, 100),
        }
        console.log(params.value)
    })
}

const chooseImg = () => {
    uni.chooseImage({
        count: 1,
        success: res => {
            const tempFiles = res.tempFiles[0]
            pictureOssPath.value = tempFiles.path
            uploadFile(tempFiles.path).then(key => {
                params.value.pictureOssPath = key
            })
        }
    })
}

const changeTag = (value) => {
    let index = params.value.deliveryTypes.indexOf(value)
    if (index === -1) {
        params.value.deliveryTypes.push(value)
    } else {
        params.value.deliveryTypes.splice(index, 1)
    }
}

const getclassify = () => {
    goodsCategories({ page: 1, size: 50 }).then(res => {
        classify.value = res.records
        if (id.value) {
            getGoodsInfo()
        }
    })
}

const selectClassify = (e) => {
    let index = e.indexs[0]
    params.value.categoryId = classify.value[index].id
    params.value.categoryName = classify.value[index].name
    showClassify.value = false
}

const onSubmit = () => {
    params.value.exchangable = exchangable.value ? 1 : 0
    params.value.marketable = marketable.value ? 1 : 0
    params.value.rentable = rentable.value ? 1 : 0
  
    const rules = {
        categoryId: { required: true },
        name: { required: true },
        unit: { required: true },
        description: { required: true },
        spec: { required: true },
        pictureOssPath: { required: true },
    }
    const messages = {
        categoryId: { required: '请输入请选择商品类目' },
        name: { required: '请输入商品名称' },
        unit: { required: '请输入商品单位' },
        description: { required: '请输入商品描述' },
        spec: { required: '请输入商品规格' },
        pictureOssPath: { required: '请上传商品封面图' },
    }
    if (params.value.rentable) {
        rules.deposit = { required: true, price: true }
        rules.priceForYear = { required: true, price: true }
        rules.priceForMonth = { required: true, price: true }
        rules.priceForWeek = { required: true, price: true }
        messages.deposit = { required: '请输入押金', price: '押金只能输入数字，最多2位小数' }
        messages.priceForYear = { required: '请输入年租金', price: '年租金只能输入数字，最多2位小数' }
        messages.priceForMonth = { required: '请输入月租金', price: '月租金只能输入数字，最多2位小数' }
        messages.priceForWeek = { required: '请输入周租金', price: '周租金只能输入数字，最多2位小数' }
    }
    if (params.value.marketable) {
        rules.price = { required: true, price: true }
        rules.vipPrice = { required: true, price: true }
        rules.wholeSalePrice = { required: true, price: true }
        messages.price = { required: '请输入零售价', price: '零售价只能输入数字，最多2位小数' }
        messages.vipPrice = { required: '请输入VIP价', price: 'VIP价只能输入数字，最多2位小数' }
        messages.wholeSalePrice = { required: '请输入批发价', price: '批发价只能输入数字，最多2位小数' }
    }
    if (params.value.rentable || params.value.marketable || params.value.exchangable) {
        rules.deliveryTypes = { required: true }
        rules.deliveryPrice = { required: true, price: true }
        rules.logisticsFee = { required: true, price: true }
        messages.deliveryTypes = { required: '请选择交付方式' }
        messages.deliveryPrice = { required: '请输入配送价', price: '配送价只能输入数字，最多2位小数' }
        messages.logisticsFee = { required: '请输入运费', price: '运费只能输入数字，最多2位小数' }
    }
    
    const wxv = new WxValidate(rules, messages)
    wxv.addMethod('price', (value, param) => {
        let num = bcmul(value, 100)
        let reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/
        return reg.test(num)
    }, '请输入最多2位小数的数字')
    if (!wxv.checkForm(params.value)) {
        const error = wxv.errorList[0]
        showToast(error.msg)
        return false
    }
    
    const data = JSON.parse(JSON.stringify(params.value))
    data.price = bcmul(data.price, 100)
    data.vipPrice = bcmul(data.vipPrice, 100)
    data.wholeSalePrice = bcmul(data.wholeSalePrice, 100)
    data.deliveryPrice = bcmul(data.deliveryPrice, 100)
    data.logisticsFee = bcmul(data.logisticsFee, 100)
    data.deposit = bcmul(data.deposit, 100)
    data.priceForYear = bcmul(data.priceForYear, 100)
    data.priceForMonth = bcmul(data.priceForMonth, 100)
    data.priceForWeek = bcmul(data.priceForWeek, 100)
    console.log(data)
    if (id.value) {
        data.id = id.value
    }
    
    loading.value = true
    addGoods(data).then(res => {
        loading.value = false
        uni.$emit('refresh_goods')
        showToast('保存成功', () => {
            backpage()
        })
    }).catch(e => {
        loading.value = false
    })
}
</script>

<style lang="scss">
.address {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    background-color: #fff;
    &-form {
        margin-top: 20rpx;
        background-color: #fff;
        padding: 0 $zzk-margin 120rpx;
    }
    &-line {
        padding: 20rpx 0;
        border-bottom: #f5f5f5 1rpx solid;
        .label {
            width: 160rpx;
            line-height: 80rpx;
            font-size: 28rpx;
            &.long {
                width: 240rpx;
            }
        }
        .value {
            align-items: center;
            flex: 1;
            &.f {
                justify-content: center;
                align-items: flex-start;
            }
        }
        .txt {
            font-size: 28rpx;
            color: #333;
            line-height: 80rpx;
            flex: 1;
            &.gray {
                color: #c0c4cc;
            }
        }
        .codebtn {
            width: 200rpx;
        }
        .input {
            flex: 1;
        }
        .img {
            width: 160rpx;
            height: 160rpx;
            display: block;
            border-radius: 8rpx;
        }
        .tag {
            background-color: #f5f5f5;
            font-size: 24rpx;
            line-height: 48rpx;
            padding: 0 16rpx;
            border-radius: 4rpx;
            margin-right: 16rpx;
            color: #999;
            &.active {
                background-color: $u-error-light;
                color: $u-error;
            }
        }
    }
    &-bottom {
        flex: 1;
        padding: 0 $zzk-margin;
        align-items: center;
    }
    &-upload {
        border: #ccc 1rpx dashed;
        border-radius: 8rpx;
        height: 160rpx;
        width: 160rpx;
        justify-content: center;
        align-items: center;
        .tip {
            font-size: 24rpx;
            line-height: 40rpx;
            color: #999;
        }
    }
}
</style>